import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'view-design'
import { setToken, getToken, canTurnTo, setTitle,hasChild } from '@/libs/util'
import config from '@/config'
import { initRouter } from '@/libs/router-util'
import {stream} from "xlsx";
const { homeName } = config

const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router)
const router = new Router({
  routes,
  mode: 'history'
})
const LOGIN_PAGE_NAME = 'login'

const turnTo = (to, access, next) => {
  initRouter()
  // 使用router.options.routes 替代 routes 防止初次登陆routes未加载菜单路由
  // router.options.routes在initRouter中已经赋值
  unionRoutes(routes,router.options.routes)
  let result = hasAccess(routes, to)
  if (result === true || to.name === homeName) next()
  else next({replace: true, name: 'error_401'})

}

const unionRoutes=(initList,menuList)=> {
  menuList.forEach(item => {
    let li = initList.filter(c => c.name == item.name);
    if (li.length == 0) {
      initList.push(item)
    }
  })
}

const hasAccess=(list,to)=> {
  let result = false;
  for (let index=0;index<list.length;index++) {
    if (list[index].name === to.name) {
      result = true
      break;
    }
    if (hasChild(list[index])) {
      for (let j = 0; j < list[index].children.length; j++) {
        if (list[index].children[j].name === to.name) {
          result = true
          break;
        }
      }
    }
  }
  return result
}

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = getToken()

  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    })
  } else {
    turnTo(to, store.state.user.access, next)
    if (store.state.user.hasGetInfo) {

    }
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
